package com.lungle.warmdiary.app.base;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.MySwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;

import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppConstant;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.api.exception.ApiException;
import com.lungle.warmdiary.app.model.Entity;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.ui.empty.EmptyLayout;
import com.lungle.warmdiary.app.utils.LogUtils;
import com.lungle.warmdiary.app.utils.TDevice;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.io.IOException;
import java.io.InputStream;

import retrofit2.adapter.rxjava.HttpException;


public class BaseDetailFragment extends BaseFragment implements MySwipeRefreshLayout.OnRefreshListener {// OnItemClickListener
    private static final String TAG = "BaseDetailFragment";


    protected MySwipeRefreshLayout mRefreshView;
    protected EmptyLayout mEmptyLayout;

    private float mDownX, mDownY;
    private boolean mLoadCacheSuccess;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRefreshView = (MySwipeRefreshLayout) view.findViewById(R.id.srl_refresh);
        mEmptyLayout = (EmptyLayout) view.findViewById(R.id.error_layout);
        if (mRefreshView != null) {
            mRefreshView.setColorSchemeResources(R.color.main_red, R.color.main_gray, R.color.main_black, R.color.main_purple);
            mRefreshView.setOnRefreshListener(this);
        }

        requestData();

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        //cancelReadCache();
        super.onDestroy();
    }

    @Override
    public void onRefresh() {
        sendRequestData();
    }


    public BaseSubscriber getSubscriber() {
        return new BaseSubscriber<Result<?>>() {
            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                if (e instanceof HttpException) {
                    AppContext.showToastShort("服务暂不可用");
                } else if (e instanceof IOException) {
                    AppContext.showToastShort("无法连接服务器");
                } else if (e instanceof ApiException) {
                    ApiException exception = (ApiException) e;
                    if (exception.isTokenExpried()) {
                        AppContext.showToast(exception.getMessage());
                    } else {
                        AppContext.showToast(e.getMessage());
                    }
                }
                LogUtils.printLogW(e.getMessage());
                executeOnLoadDataError(e.getMessage());
                executeOnLoadFinish();

            }

            @Override
            public void onNext(Result<?> result) {
                if (result.isOk()) {
                    Entity entry = (Entity) result.getData();
                    if (entry != null) {
                        if (mEmptyLayout != null)
                            mEmptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                        executeOnLoadDataSuccess(entry);
                        executeOnLoadFinish();
                    } else {
                        executeOnLoadDataError(null);
                    }

                }
            }


        };
    }


    protected void requestData() {
        if (mEmptyLayout != null)
            mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
        sendRequestData();
    }


    protected String getCacheKey() {
        return null;
    }

    protected long getCacheExpore() {
        return AppConstant.CACHE_EXPIRE_OND_DAY;
    }

    protected Entity parseData(InputStream is) throws Exception {
        return null;
    }


    protected void sendRequestData() {
    }

    protected void executeOnLoadDataSuccess(Entity entity) {
    }


    protected void executeOnLoadDataError(String object) {
        if (mLoadCacheSuccess) {
            if (TDevice.hasInternet())
                AppContext.showToastShort(R.string.tip_load_data_error);
            else
                AppContext.showToastShort(R.string.tip_network_error);
        } else {
            mEmptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
            mEmptyLayout.setOnLayoutClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    mState = STATE_REFRESH;
                    mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                    //requestData(true);
                    sendRequestData();
                }
            });
        }
    }

    protected void executeOnLoadFinish() {
        if (mRefreshView != null)
            mRefreshView.setRefreshing(false);
    }


    protected void shareToWechatCicle(String title, String content, String imageUrl, String link) {
        shareTo(this.getActivity(), title, content, imageUrl, link, SHARE_MEDIA.WEIXIN_CIRCLE);
    }

    private void shareTo(Activity activity, String title, String content, String imageUrl, String link, SHARE_MEDIA platform) {
        ShareAction shareAction = new ShareAction(activity);
        if (!TextUtils.isEmpty(title)) {
            shareAction.withTitle(title);
        }
        if (!TextUtils.isEmpty(content)) {
            shareAction.withText(content);
        }

        if (!TextUtils.isEmpty(imageUrl)) {
            UMImage umImage = new UMImage(activity, imageUrl);
            shareAction.withMedia(umImage);
        }


        if (!TextUtils.isEmpty(link)) {
            shareAction.withTargetUrl(link);
        }
        shareAction.setPlatform(platform).setCallback(mUMShareListener).share();

    }

    protected UMShareListener mUMShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA share_media) {
            AppContext.showToast("success");
        }

        @Override
        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
            AppContext.showToast("error");
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {
            AppContext.showToast("cancle");
        }
    };


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(getActivity()).onActivityResult(requestCode, resultCode, data);
    }


}
